package com.kinon.ceshiaccount.fragment.home;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.kinon.ceshiaccount.R;
import com.kinon.ceshiaccount.activity.OrderPayActivity;
import com.kinon.ceshiaccount.adapter.DishesAdapter;
import com.kinon.ceshiaccount.adapter.MenuAdapter;
import com.kinon.ceshiaccount.application.AccountApplication;
import com.kinon.ceshiaccount.bean.CookbooksBean;
import com.kinon.ceshiaccount.bean.RoleBean;
import com.kinon.ceshiaccount.bean.base.BaseBean;
import com.kinon.ceshiaccount.bean.menu.Breakfast;
import com.kinon.ceshiaccount.bean.menu.NewCookbooks;
import com.kinon.ceshiaccount.bean.menu.SelDisches;
import com.kinon.ceshiaccount.constant.Constant;
import com.kinon.ceshiaccount.fragment.BaseFragment;
import com.kinon.ceshiaccount.network.HttpManage;
import com.kinon.ceshiaccount.network.MyCallback;
import com.kinon.ceshiaccount.network.StrCallback;
import com.kinon.ceshiaccount.util.MyDecimalFormat;
import com.kinon.ceshiaccount.util.MyShowDialog;
import com.kinon.ceshiaccount.util.SPManage;
import com.kinon.ceshiaccount.util.ToastUtil;

import java.util.ArrayList;

import retrofit2.Call;
import retrofit2.Response;


/**
 * Created by luohao on 2017-06-16.
 * 结算页面，负责金额计算生成结算订单
 */

public class GoodsFragment extends BaseFragment implements View.OnClickListener, RadioGroup.OnCheckedChangeListener
        , DishesAdapter.DishesClickListener {
    ToastUtil toastUtil = new ToastUtil();
    private View mView;
    private TextView tv_menuType;
    private TextView btn_clearMenu;
    private GridView gv_menu;
    private ListView lv_dishes;
    private TextView tv_num;
    private TextView tv_totalPrice;
    private TextView tv_seltte;

    /**选择就餐类型*/
//    private GridView grid_diningType;
    private RadioGroup rg_menuType;
    /**
     * 显示就餐类型的布局
     */
    private RelativeLayout rl_select;
    private Context context;
    private MenuAdapter mMenuAdapter;
    private ArrayList<Breakfast> menuList;
    private ArrayList<Breakfast> menuTypeList;
    private ArrayList<SelDisches> disList;
    private ArrayList<CookbooksBean.Category> categoryLiset;
    private DishesAdapter mDisAdapter;
    private int totalNum = 0;
    private double totalPriice = 0.0;
    private CookbooksBean cooks = null;
    /*就餐类型相关*/
    private int mType = 0;
    private ArrayList<RoleBean> binings = null;
    //    private DiningTypeAdapter diningAdapter=null;
    private int mIndex = 0;
    private long firstTime;
    private int itemWidth = 110;
    private int menuTypeIndex = 0;
    private AdapterView.OnItemClickListener itemListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            int amount = menuTypeList.get(i).getAmount();
            int id = menuTypeList.get(i).getId();
            boolean isSame = false;
            for (int d = 0; d < disList.size(); d++) {
                if (id == disList.get(d).getProductid()) {
                    disList.get(d).setNum(disList.get(d).getNum() + 1);
                    isSame = true;
                    break;
                }
            }
            if (!isSame) {
                disList.add(0, new SelDisches(id,
                        menuTypeList.get(i).getName(), menuTypeList.get(i).getPrice(),
                        1, i));
            }

//            if(amount!=0){
//                for(int d=0;d<disList.size();d++) {
//                    if (menuTypeList.get(i).getProductid() == disList.get(d).getProductid()) {
//                        disList.get(d).setNum(disList.get(d).getNum() + 1);
//                        break;
//                    }
//                }
//            }else{
//                disList.add(0,new SelDisches(menuTypeList.get(i).getProductid(),
//                        menuTypeList.get(i).getName(),menuTypeList.get(i).getPrice(),
//                        1,i));
//            }
//            menuTypeList.get(i).setAmount(amount+1);
            totalNum++;
            totalPriice += menuTypeList.get(i).getPrice();
            setNumPrice(totalNum, totalPriice);

        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragement_menu_layout, container, false);
        return mView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            dataClear();
//            couItemWidth();
//            mMenuAdapter.setmWidth(itemWidth);
            if (binings != null /*&& diningAdapter!=null*/) {
                int timeArea = (int) ((System.currentTimeMillis() - firstTime) / (1000 * 60 * 60));
//                setDiningType();
                if (timeArea >= 2) {
//                    dialogSelect();
                }
            }
        } else {

        }
    }

    private void initView() {
        context = AccountApplication.getInstance();
        tv_menuType = (TextView) mView.findViewById(R.id.tv_menuType);
        btn_clearMenu = (TextView) mView.findViewById(R.id.btn_clearMenu);
        gv_menu = (GridView) mView.findViewById(R.id.gv_menu);
        lv_dishes = (ListView) mView.findViewById(R.id.lv_dishes);
        tv_num = (TextView) mView.findViewById(R.id.tv_num);
        tv_totalPrice = (TextView) mView.findViewById(R.id.tv_totalPrice);
        tv_seltte = (TextView) mView.findViewById(R.id.tv_seltte);
//        grid_diningType= (GridView) mView.findViewById(R.id.grid_diningType);
        rl_select = (RelativeLayout) mView.findViewById(R.id.rl_select);
        rg_menuType = (RadioGroup) mView.findViewById(R.id.rg_menuType);
        tv_menuType.setVisibility(View.GONE);
        couItemWidth();
        menuList = new ArrayList<>();
        menuTypeList = new ArrayList<>();
        disList = new ArrayList<>();
        mDisAdapter = new DishesAdapter(disList, mContext);
        lv_dishes.setAdapter(mDisAdapter);
        mMenuAdapter = new MenuAdapter(menuTypeList, mContext, itemWidth);
        gv_menu.setAdapter(mMenuAdapter);

        getCookbooks();
        addClick();

    }
    /**显示就餐类型*/
//    private void showDiningType(){
//        String roles=SPManage.getInstance().getString("roles");
//        if (TextUtils.isEmpty(roles)){
//            return;
//        }
//        Gson gson=new Gson();
//        binings=new ArrayList<>();
//        try {
//            JSONArray array=new JSONArray(roles);
//            for(int i=0;i<array.length();i++){
//                RoleBean bean=gson.fromJson(array.get(i).toString(),RoleBean.class);
//                //显示固定的几种
//                if(bean.getId()==0 || bean.getId()==1 ||bean.getId()==3 ) {
//                    binings.add(bean);
//                }
//            }
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
//        if(binings.size()==0){
//            rl_select.setVisibility(View.GONE);
//            return;
//        }
//
//        mType=binings.get(0).getId();
////        tv_menuType.setText(LunchTypeUtil.lunchType(mType));
//        if(binings.size()==1){
//            rl_select.setVisibility(View.GONE);
////            setShowData();
//            return;
//        }
//
//        setDiningType();
//        dialogSelect();
//    }

    /**
     * 计算餐单的宽度
     */
    private void couItemWidth() {
        int menuNum = SPManage.getInstance().getInt("mune_line_num", 8);
        gv_menu.setNumColumns(menuNum);
        int menuWidth = AccountApplication.SCREEN_HEIGHT
                / 4 * 3 - (menuNum - 1) * 4;
        itemWidth = menuWidth / menuNum;
    }

    /**
     * 获取默认的刷卡类型
     */
//    private void setDiningType(){
//        int  type= SysTimeManage.getInstage().getOrderType(System.currentTimeMillis());
//        for(int i=0;i<binings.size();i++){
//            if(binings.get(i).getId()==type){
//                mIndex=i;
//                mType=type;
//                continue;
//            }
//        }
////        setShowData();
////        diningAdapter.selectItem(mIndex);
////        diningAdapter.notifyDataSetChanged();
////        tv_menuType.setText(LunchTypeUtil.lunchType(mType));
//    }

//    private void dialogSelect(){
//        firstTime=System.currentTimeMillis();
//        CustomDialog dialog=new CustomDialog(1, getContext(),null, binings,
//                mIndex,new CustomDialog.DialogClickListener() {
//            @Override
//            public void onDialogClick(int btn) {
////                        Log.e("lh", "btn== "+btn );
//                mIndex=btn;
//                mType=binings.get(btn).getId();
////                tv_menuType.setText(LunchTypeUtil.lunchType(mType));
//                dataClear();
//                setShowData();
//            }
//        });
//        dialog.show();
//    }
    private void addClick() {
        mDisAdapter.setDishesClickListener(this);
        gv_menu.setOnItemClickListener(itemListener);
        tv_seltte.setOnClickListener(this);
//        tv_menuType.setOnClickListener(this);
        btn_clearMenu.setOnClickListener(this);
        rg_menuType.setOnCheckedChangeListener(this);
    }

    /**
     * 获取菜单
     */
    private void getCookbooks() {
//        Log.e("lh", "token== "+SPManage.getInstance().getToken());
        Call<String> call = HttpManage.getRequestApi()
                .getNewCookbooks(SPManage.getInstance().getToken());
        call.enqueue(new StrCallback<String>() {
            @Override
            public void onSuccess(Response<String> response, String data) {
                Gson gson = new Gson();
                NewCookbooks bean = gson.fromJson(data, NewCookbooks.class);

//                try {
//                    JSONArray array =new JSONArray(data);
//                    for(int i=0;i<array.length();i++){
//                        Breakfast bean=gson.fromJson(array.get(i).toString(),Breakfast.class);
//
//                    }
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
                menuTypeList.addAll(bean.getProducts());
                mType = bean.getType();
                mMenuAdapter.notifyDataSetChanged();

//                categoryLiset=cooks.getCategory();
//                setShowData();
//                showMenuType();
//                showDiningType();
            }

            @Override
            public void onError(int code, String error) {
                toastUtil.Short(error)
                        .setToastBackground(Color.WHITE, 0).show();
//                Toast.makeText(mContext,error+"",
//                        Toast.LENGTH_SHORT).show();

            }
        });
    }

    /**
     * 显示餐单
     */
//    private void setShowData(){
////        menuTypeList.clear();
//        menuList.clear();
//        if(cooks==null){
//           return;
//        }
//        if(mType==0){
//            menuList.addAll(cooks.getCookbooks().getBreakfast());
//        }else if(mType==1){
//            menuList.addAll(cooks.getCookbooks().getLunch());
//        }else if(mType==3){
//            menuList.addAll(cooks.getCookbooks().getDinner());
//        }
//
//        addMenuTypeLiset(menuTypeIndex);
//    }
    @Override
    public void ondishesClick(int position, int type) {
        int num = disList.get(position).getNum();
        numPriceCount(position, type);
        if (type == 0) {
            if (num > 1) {
                disList.get(position).setNum(num - 1);
            } else {
                disList.remove(position);
            }
        } else {
            disList.get(position).setNum(num + 1);
        }
        mDisAdapter.notifyDataSetChanged();
    }

    /**
     * 提交订单
     */
    private void saveProductOrder() {
        if (disList.size() <= 0) {
            toastUtil.Short("请选择商品")
                    .setToastBackground(Color.WHITE, 0).show();
            return;
        }
        long nonce_str = System.currentTimeMillis();

        Gson gson = new Gson();
        String strData = gson.toJson(disList);

        if (!Constant.URGENT_TYPE) {
            callsaveProductOrder(strData, nonce_str + "");
        } else {
            urgentJiesuan(true, "", nonce_str + "", strData);
        }

    }

    private void callsaveProductOrder(final String strData, final String nonce_str) {
        Log.e(TAG, "strData== " + strData);
        Log.e(TAG, "mType== " + mType);
        Call<BaseBean<String>> call = HttpManage.getReqLunchApi()
                .saveProductOrder(SPManage.getInstance().getToken()
                        , mType + "", totalPriice + "", strData, nonce_str);
        MyShowDialog.showLoadingDialog(getActivity(), "结算中");
        call.enqueue(new MyCallback<BaseBean<String>>() {
            @Override
            public void onSuccess(Call<BaseBean<String>> call, Response<BaseBean<String>> response) {
                MyShowDialog.closeLoadingDialog();
                BaseBean<String> base = response.body();
                urgentJiesuan(false, base.getData(), nonce_str, "");
            }

            @Override
            public void onError(int code, String error) {
                MyShowDialog.closeLoadingDialog();
                if (code == Constant.ERROR_TIMEOUT_CODE) {
                    urgentJiesuan(false, "", nonce_str, strData);
                } else {
                    toastUtil.Short("error")
                            .setToastBackground(Color.WHITE, 0).show();
//                    Toast.makeText(context,error,Toast.LENGTH_SHORT).show();
                }

            }
        });
    }


    /**
     * 紧急结算 urgent=true紧急模式
     */
    private void urgentJiesuan(boolean urgent, String orderid,
                               String nonce_str, String detail) {
        Intent intent = new Intent(getContext(), OrderPayActivity.class);
        intent.putExtra("total", totalPriice + "");
        intent.putExtra("diningType", mType);
        intent.putExtra("oridrid", orderid);
        intent.putExtra("urgent", urgent);
        intent.putExtra("nonce_str", nonce_str);
        intent.putExtra("orderDetail", detail);
        startActivity(intent);
        //完成跳转然后清空数据
        dataClear();
    }

    //计算数量和价格
    private void numPriceCount(int position, int count) {
        if (count == 0) {
            totalNum--;
            totalPriice -= disList.get(position).getPrice();
        } else {
            totalNum++;
            totalPriice += disList.get(position).getPrice();
        }
        setNumPrice(totalNum, totalPriice);
    }

    private void setNumPrice(int totalNum, double totalPrice) {
        String strTotal = "0";
        if (String.valueOf(totalPrice).length() > 8) {
            strTotal = MyDecimalFormat.dFormat(totalPrice);
            totalPriice = Double.valueOf(strTotal);
        }
        tv_num.setText(totalNum + "");
        tv_totalPrice.setText(String.valueOf(totalPriice));
        mDisAdapter.notifyDataSetChanged();
//        mMenuAdapter.notifyDataSetChanged();
    }

    /**
     * 清空数据
     */
    private void dataClear() {
//        for(int i=0;i<disList.size();i++){
//            menuTypeList.get(disList.get(i).getIndex()).setAmount(0);
//        }
        disList.clear();
        totalNum = 0;
        totalPriice = 0.0;
        setNumPrice(0, 0.0);
        mDisAdapter.notifyDataSetChanged();
//        mMenuAdapter.notifyDataSetChanged();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_clearMenu:
                dataClear();
                break;
            case R.id.tv_seltte:
                saveProductOrder();
                break;
//            case R.id.tv_menuType:
////                dialogSelect();
//            break;
            default:
                break;
        }
    }

    /**
     * 画出商品分类
     */
    private void showMenuType() {
        if (categoryLiset == null || categoryLiset.size() <= 1) {
            rg_menuType.setVisibility(View.GONE);
            return;
        }
        rg_menuType.removeAllViews();
        RadioGroup.LayoutParams lp = new RadioGroup.LayoutParams
                (RadioGroup.LayoutParams.MATCH_PARENT,
                        RadioGroup.LayoutParams.WRAP_CONTENT, 1);
        lp.gravity = Gravity.CENTER;
        for (int i = 0; i < categoryLiset.size(); i++) {
            RadioButton rb = new RadioButton(getActivity());
            rb.setId(i);
            rb.setWidth(0);
            rb.setHeight(RadioGroup.LayoutParams.WRAP_CONTENT);
            rb.setGravity(Gravity.CENTER);
            rb.setBackgroundResource(R.drawable.img_menutype_select);
            rb.setButtonDrawable(android.R.color.transparent);
            rb.setTextSize(18);
            rb.setTextColor(getResources().getColorStateList(R.color.color_menutype_select));
//            rb.setTextColor(getResources().getColor(R.color.color_menutype_select));
            rb.setText(categoryLiset.get(i).getName());
            rg_menuType.addView(rb, lp);
        }
        ((RadioButton) rg_menuType.getChildAt(0)).setChecked(true);
//        rg_menuType.
        addMenuTypeLiset(0);

    }

    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int i) {
        menuTypeIndex = i;
        addMenuTypeLiset(i);
    }

    /**
     * 获取早午晚餐的商品
     */
    private void addMenuTypeLiset(int position) {
        menuTypeList.clear();
        for (Breakfast m : menuList) {
            if (m.getCategoryid() == categoryLiset.get(position).getId()) {
                menuTypeList.add(m);
            }
        }

        mMenuAdapter.notifyDataSetChanged();
    }
}
